﻿using BrnMall.CacheManager;
using System;
using System.Web;
using System.Web.Caching;
using System.Web.SessionState;

namespace BrnMall.Sms
{
    public class SMSHelper
    {
        /// <summary>
        /// 验证码发送的类型-注册
        /// </summary>
        private const int TYPE_REGIST = 1;
        /// <summary>
        /// 验证码发送的类型-登录
        /// </summary>
        private const int TYPE_LOGIN = 2;
        /// <summary>
        /// 验证码发送的类型-修改手机号
        /// </summary>
        private const int TYPE_MODIFY = 4;

        /// <summary>
        /// 生成随机code
        /// </summary>
        /// <returns></returns>
        public static string MakeCode()
        {
            return new Random().Next(100000, 999999).ToString();
        }
        /// <summary>
        /// 生成并发送验证码
        /// </summary>
        /// <param name="phone">接收验证码的手机号</param>
        /// <param name="type">验证码发送类型</param>
        /// <returns></returns>
        public static bool SendCode(string phone, int type)
        {
            var time = GetCodeTime();

            if (!string.IsNullOrEmpty(time))
            {
                //验证码发送过于频繁
                var secends = DateTime.Now.Subtract(Convert.ToDateTime(time)).TotalSeconds;
                if (secends <Config.SMS_CODE_TIMEOUT)
                    return false;
            }

            ////得到已经保存到session的验证码信息
            SMSCodeBean bean = HttpContext.Current.Session["code"] as SMSCodeBean;
            var key = string.Format(CacheKeys.PC_SMS_CODE, phone);
            var aa = BMACache.Get<SMSCodeBean>(key);
            if (BMACache.Exists(key)) { var cc = BMACache.Get<SMSCodeBean>(key); }
            if (aa != null && (DateTime.Now - aa.Time).TotalMilliseconds < Config.SMS_CODE_TIMEOUT)
            {
                //验证码发送过于频繁
                return false;
            }

            var code = MakeCode();
            bool isSuccess = false;

            switch (type)
            {
                case TYPE_REGIST:
                    isSuccess = AliSMS.SendRegistCode(phone, code);
                    break;
                case TYPE_LOGIN:
                    isSuccess = AliSMS.SendLoginCode(phone, code);
                    break;
                case TYPE_MODIFY:
                    isSuccess = AliSMS.SendModifyCode(phone, code);
                    break;
                default:
                    break;
            }

            if (isSuccess)
            {
                ////封装验证码信息并保存到session
                SMSCodeBean newCode = new SMSCodeBean { Code = code, Phone = phone, Time = DateTime.Now };
                BMACache.Insert<SMSCodeBean>(key, newCode);
                BMACache.TimeOut = 100000000;
                HttpContext.Current.Session["code"] = newCode;
                return true;
            }
            else
                return false;
        }
        /// <summary>
        /// 验证码验证
        /// </summary>
        /// <param name="phone">手机号</param>
        /// <param name="code">验证码</param>
        /// <returns></returns>
        public static bool ValidateCode(String phone, String code)
        {
            //HttpSessionState session = HttpContext.Current.Session;
            //得到已经保存到session的验证码信息  
            var bb = HttpContext.Current.Session["code"].ToString();
            var key = string.Format(CacheKeys.PC_SMS_CODE, phone);
            var aa = BMACache.Get<SMSCodeBean>(key);
            if (code == null || code != aa.Code)
            {
                //验证码不正确或已过期
                return false;
            }
            else
            {
                //验证成功清除该session
                //session.Remove(SMS_CODE_SESSION_NAME);
                BMACache.Remove(key);
                return true;
            }
        }

        /// <summary>
        /// 注册,这里没有验证手机号,请在调用此方法之前验证手机号是否合法
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static bool Regist(string phone)
        {
            return SendCode(phone, TYPE_REGIST);
        }

        /// <summary>
        /// 登录,这里没有验证手机号,请在调用此方法之前验证手机号是否合法
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static bool Login(string phone)
        {
            return SendCode(phone, TYPE_LOGIN);
        }

        /// <summary>
        /// 修改手机号,这里没有验证手机号,请在调用此方法之前验证手机号是否合法
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static bool Modify(string phone)
        {
            return SendCode(phone, TYPE_MODIFY);
        }

        static string GetCode()
        {
            HttpRequest Request = HttpContext.Current.Request;
            var cookie = Request.Cookies.Get("weapp_sms");
            return cookie == null ? "" : cookie.Value;
        }

        static void SetCode(string code)
        {
            HttpResponse Response = HttpContext.Current.Response;
            var cookie = new HttpCookie("weapp_sms");
            cookie.Values["time"] = DateTime.Now.ToString();
            cookie.Values["code"] = code;
            cookie.Expires = DateTime.Now.AddSeconds(Config.SMS_CODE_TIMEOUT);
            Response.Cookies.Add(cookie);
        }

        static string GetCodeTime()
        {
            HttpRequest Request = HttpContext.Current.Request;
            var cookie = Request.Cookies.Get("weapp_sms");
            return cookie == null ? "" : cookie.Values["time"];
        }

    }
}